<template>
  <el-dialog
    :close-on-click-modal="false"
    :title="view ? '查看合同' : (isEdit ? '修改合同' : '新增合同')"
    width="900px"
    :visible.sync="visible"
  >
    <h3>合同基本信息</h3>
    <el-form :model="form" :rules="rules" :disabled="view" ref="form" label-width="110px">
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="合同名称" prop="contractName">
            <el-input v-model="form.contractName" placeholder="请输入合同名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同编号" prop="contractNo">
            <el-input v-model="form.contractNo" placeholder="请输入合同编号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供应商名称" prop="supplierName">
            <!-- <el-autocomplete
              style="width: 100%"
              v-model="form.supplierName"
              :fetch-suggestions="(queryString, cb) => supplierQueryAsync(queryString, cb, true, 'supplier')"
              placeholder="请输入供应商名称"
              @select="value => supplierSelect(value, 'supplierName', 'supplierCode')"
            />-->
            <el-input :readOnly="true" v-model="form.supplierName" placeholder="请输入供应商名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="第三方">
            <el-input v-model="form.thirdParty" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同类型" prop="contractType">
            <el-select clearable style="width: 100%" v-model="form.contractType">
              <el-option
                :label="item.label"
                :value="item.value"
                v-for="(item,index) in typeArr"
                :key="index"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="经办人">
            <el-input v-model="form.operatorId" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同到期日期" prop="expiryDate">
            <el-date-picker
              style="width: 100%"
              v-model="form.expiryDate"
              type="date"
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
              placeholder="选择合同到期日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同金额" prop="contractSum">
            <el-input v-model.number="form.contractSum" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="合同签订时间" prop="signDate">
            <el-date-picker
              style="width: 100%"
              format="yyyy-MM-dd"
              v-model="form.signDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择合同签订时间"
            />
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item label="付款条款" prop="paymentTerms">
            <el-input type="textarea" :rows="3" v-model="form.paymentTerms" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <h3>明细表</h3>
    <div class="mb10">
      <el-button size="small" :disabled="view" @click="handleAdd" type="primary">新增</el-button>
      <el-button
        size="small"
        @click="handleDelete"
        type="danger"
        :disabled="view || selectedRows.length === 0"
      >删除</el-button>
    </div>
    <e-table
      class="mb20"
      ref="eTable"
      @tableCheck="handleTableCheck"
      :tableData="tableData"
      :columns="columns"
      :loading="loading"
      :pageObj="null"
    >
      <el-table-column slot="selection" align="center" type="selection" width="55" />
      <el-table-column label="货物名称" slot="detail" align="center">
        <template slot-scope="scope">
          <el-input v-model="scope.row.detailName" />
        </template>
      </el-table-column>
      <el-table-column label="规格" slot="specifications" align="center">
        <template slot-scope="scope">
          <el-input v-model="scope.row.specifications" />
        </template>
      </el-table-column>
      <el-table-column label="单位" slot="unit" align="center">
        <template slot-scope="scope">
          <el-input v-model="scope.row.unit" />
        </template>
      </el-table-column>
      <el-table-column label="数量" slot="number" align="center">
        <template slot-scope="scope">
          <el-input type="number" v-model="scope.row.number" />
        </template>
      </el-table-column>
      <el-table-column label="价格" slot="price" align="center">
        <template slot-scope="scope">
          <el-input type="number" v-model="scope.row.price" />
        </template>
      </el-table-column>
      <el-table-column label="金额" slot="amount" align="center">
        <template slot-scope="scope">
          <el-input type="number" v-model="scope.row.amount" />
        </template>
      </el-table-column>
    </e-table>

    <h3>合同影印件</h3>
    <el-upload
      :disabled="view"
      action="https://jsonplaceholder.typicode.com/posts/"
      :file-list="fileList"
      class="file-upload"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :http-request="customRequest"
    >
      <span>添加附件</span>
    </el-upload>
    <preview-modal ref="previewModal" />
    <div slot="footer" v-if="!view">
      <el-button @click="visible = false">取消</el-button>
      <el-button @click="handleOk" type="primary">{{ isEdit ? '修改' : '新增' }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { fuzzyQuery, supplierFuzzyQuery, createSupplier } from '@/api/assetsNew'
import { updateContract, createContract, saveOnlyUploads, searchSupplier } from '@/api/supplier'
import { openNotification, getDicData } from '@/utils/util'
import PreviewModal from '@/components/PreviewModal'
export default {
  components: {
    PreviewModal
  },
  data() {
    return {
      isEdit: false,
      visible: false,
      view: false, // 查看
      fileList: [],
      form: {
        signDate: null,
        expiryDate: null
      },
      typeArr: [{ label: '001', value: '001' }],
      rules: {
        expiryDate: [{ required: true, message: '请选择结束日期', trigger: 'blur' }],
        signDate: [{ required: true, message: '请选择签订日期', trigger: 'blur' }],
        contractName: [{ required: true, message: '请输入合同名称', trigger: 'blur' }],
        supplierName: [{ required: true, message: '请输入供应商名称', trigger: 'blur' }],
        contractType: [{ required: true, message: '请选择合同类型', trigger: 'blur' }],
        contractNo: [{ required: true, message: '请输入合同编号', trigger: 'blur' }],
        paymentTerms: [{ required: true, message: '请输入付款条款', trigger: 'blur' }],
        contractSum: [
          { type: 'number', message: '合同金额为数字', trigger: 'blur' },
          {
            required: true,
            message: '请输入合同金额',
            trigger: 'blur'
          }
        ]
      },
      selectedRows: [],
      tableData: [],
      columns: [
        { slot: 'selection' },
        {
          slot: 'detail'
        },
        {
          slot: 'specifications'
        },
        {
          slot: 'unit'
        },
        {
          slot: 'number'
        },
        {
          slot: 'price'
        },
        {
          slot: 'amount'
        }
      ],
      loading: false,
      mdl: this.$route.params.obj || getSession('record')
    }
  },
  methods: {
    // 预览图片
    handlePreview(file) {
      let arr = []
      this.fileList.map(v => {
        arr.push(v.savePath)
      })
      this.$refs.previewModal.show(arr)
      // console.log('tableData', this.itemArr[index].tableData, ind, one)
    },
    edit(bool, row, view = false) {
      this.view = view // 查看
      this.isEdit = bool
      this.visible = true
      this.form = Object.assign({}, row)
      if (bool) {
        this.tableData = this.form.supplierContractDetails
        if (this.form.attachPathList.length > 0) {
          this.fileList = [...this.form.attachPathList]
        }
      } else {
        this.$set(this.form, 'supplierName', this.mdl.supplierName)
        this.$set(this.form, 'supplierCode', this.mdl.supplierCode)
      }
    },
    supplierFilter(queryString) {
      return state => {
        // console.log('state', state)
        return state.supplier.indexOf(queryString) >= 0
      }
    },
    handleOk() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          let res = null,
            mes = null
          let submit = true
          if (this.tableData.length > 0) {
            this.tableData.map(v => {
              if (v.detailName && v.number) {
                submit = true
              } else {
                submit = false
              }
            })
            this.$set(this.form, 'supplierContractDetails', this.tableData)
          }
          let arr = []
          if (this.fileList.length > 0) {
            this.fileList.map(v => {
              arr.push(v.uploadId)
            })
            this.$set(this.form, 'contractAttach', arr.join(','))
          }
          if (submit) {
            if (this.isEdit) {
              // 修改
              res = await updateContract(this.form)
              mes = '修改操作成功'
            } else {
              // 新增
              res = await createContract(this.form)
              mes = '新增操作成功'
            }
            if (res.state === '000000') {
              openNotification('success', mes)
              this.visible = false
              this.$emit('refresh')
              this.tableData = []
              this.fileList = []
            }
          } else {
            this.$message.error('明细表中的货物名称和数量为必填项')
          }
        }
      })
    },
    handleAdd() {
      this.tableData.push({
        xmId: this.tableData.length + 1
      })
    },
    handleDelete(row) {
      const _this = this
      this.$confirm({
        title: '删除操作',
        content: `您确定删除这条记录吗？`,
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        centered: true,
        async onOk() {
          // 调用删除接口，刷新表格数据
          this.selectedRows.map(v => {
            const index = _this.tableData.findIndex(a => a.contractDetailId === v.contractDetailId)
            _this.tableData.splice(index, 1)
          })
          //   const res = await deleteLinkMan(row.linkmanId, {})
          //   openNotification('success', '删除成功')
          //   _this.handleGetList()
        }
      })
    },
    handleTableCheck(arr) {
      this.selectedRows = arr
      console.log('selectedRows', this.selectedRows)
    },
    async supplierQueryAsync(queryString, cb, bool, mode) {
      console.log('bool', bool)
      if (mode === 'supplier') {
        this.$set(this.form, 'supplierCode', null)
      } else {
        this.$set(this.form, 'factoryCode', null)
      }
      queryString = queryString === undefined ? null : queryString
      let results = []
      if (queryString) {
        console.log('queryString', queryString)
        let res = ''
        if (bool) {
          //   res = await supplierFuzzyQuery({ supplierName: queryString })
          res = await searchSupplier({ supplier: queryString })
        } else {
          res = await fuzzyQuery({ assetsName: queryString })
        }
        var supplier = res.data
        if (queryString) {
          if (bool) {
            // 过滤供应商
            results = supplier.filter(this.supplierFilter(queryString))
          } else {
            results = supplier.filter(this.nameFilter(queryString))
          }
        } else {
          results = supplier
        }
        if (bool) {
          results.map(v => {
            v.value = v.supplier
          })
        } else {
          results.map(v => {
            v.value = v.assetsName
          })
        }
        // console.log('results', results)
        if (results.length === 0) {
          if (bool) {
            // 供应商
            results.push({
              value: queryString,
              supplier: queryString,
              supplierId: '-1'
            })
          }
        }

        clearTimeout(this.timeout)
        this.timeout = setTimeout(() => {
          cb(results)
        }, 1000 * Math.random())
      } else {
        clearTimeout(this.timeout)
        this.timeout = setTimeout(() => {
          cb(results)
        }, 300 * Math.random())
      }
    },
    async supplierSelect(value, key, code) {
      //   console.log('supplierSelect', value, key)
      if (value.supplierId === '-1') {
        // const res = await createSupplier({ name: value.supplier })
        // console.log('res', res)
        console.log('code', code, value)
        this.$set(this.form, 'supplierName', value.supplier)
        this.$set(this.form, 'supplierCode', null)
      } else {
        this.$set(this.form, code, value.supplierId)
      }
      this.$set(this.form, key, value.supplier)
      console.log('form', this.form)
    },
    handleRemove(info) {
      const index = this.fileList.findIndex(v => v.uploadId === info.uploadId)
      this.fileList.splice(index, 1)
    },
    // 覆盖原本的上传方法
    customRequest(info, local) {
      const formData = new FormData()
      formData.append('file', info.file)
      // 调方法，post，body 放入 formData
      saveOnlyUploads(formData).then(res => {
        if (res.data !== null) {
          const { data } = res
          console.log('data', data)
          this.fileList.push(data)
          this.fileList[this.fileList.length - 1].status = 'done'
          this.fileList[this.fileList.length - 1].uploadId = data.uploadId
          this.fileList[this.fileList.length - 1].savePath = data.fileUrl + data.fileName
          this.fileList[this.fileList.length - 1].url = data.fileUrl + data.fileName
          this.fileList[this.fileList.length - 1].name = info.file.name

          console.log('fileList', this.fileList)
        }
      })
    }
  },
  created() {
    this.typeArr = getDicData('002', '002008')
  }
}
</script>
